#include <stdio.h>
#include <stdlib.h>

#include "../../include/dlist.h"


static void print_dlist(const dlist_t *dlist)
{
	unsigned int idx = 0;
	dlist_node_t *n;
	
	if (!dlist){
		fprintf(stderr, "dlist is null!\n");
		return;
	}

	fprintf(stdout, "dlist size is %d\n", dlist_size(dlist));
	n = dlist_head(dlist);
	
	while(1)
	{
		fprintf(stdout, "dlist[%03d] = %03d\n", idx, *(int *)dlist_data(n));
		idx++;

		if (dlist_is_tail(n))
			break;
		else
			n = dlist_next(n);
	}

	return;
}

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[])
{
	dlist_t dlist;
	dlist_node_t	*n;
	unsigned int idx;
	int *data;
	int ret;

	dlist_init(&dlist, free);
	for (idx = 10; idx > 0; idx--)
	{
		if (!(data = (int *)malloc(sizeof(int)))){
			fprintf(stdout, "data malloc failed\n");
			return -1;
		}

		*data = idx;
		if (dlist_insert_prev(&dlist, dlist_head(&dlist), data)){
			fprintf(stdout, "data insert failed\n");
			return -1;
		}
	}
	print_dlist(&dlist);

	
	n = dlist_head(&dlist);
	for (idx = 0; idx < 7; idx++)
	{
		n = dlist_next(n);
	}
	
	fprintf(stdout, "ready to remove list[%03d] = %03d\n", 
			idx, *(int *)dlist_data(n));

	ret = dlist_remove(&dlist, n, (void **)&data);
	if (ret)
		return -1;
	print_dlist(&dlist);

	*data = 11;
	fprintf(stdout, "insert %d after tail \n", *data);
	ret = dlist_insert_next(&dlist, dlist_tail(&dlist), (void *)data);
	if (ret)
		return -1;
	print_dlist(&dlist);

	fprintf(stdout, "remove after head\n");
	ret = dlist_remove(&dlist, dlist_head(&dlist), (void **)&data);
	if (ret)
		return -1;
	print_dlist(&dlist);

	fprintf(stdout, "insert 12 after head\n");
	*data = 12;
	ret = dlist_insert_next(&dlist, dlist_head(&dlist), (void *)data);
	print_dlist(&dlist);

	ret = dlist_is_head(dlist_head(&dlist));
	fprintf(stdout, "testing dlist_is_head...result = %d\n", ret);

	ret = dlist_is_tail(dlist_tail(&dlist));
	fprintf(stdout, "testing dlist_is_tail...result = %d\n", ret);
	
	ret = dlist_is_head(dlist_tail(&dlist));
	fprintf(stdout, "testing dlist_is_head...result = %d\n", ret);
	
	ret = dlist_is_tail(dlist_head(&dlist));
	fprintf(stdout, "testing dlist_is_tail...result = %d\n", ret);

	dlist_destroy(&dlist);

	return 0;
}
